package sample.client.view;

import javax.inject.Named;

import sample.client.CMModel;
import sample.client.ClientManagerService;
import sample.client.ClientManagerServiceAsync;
import sample.client.DocumentList;
import sample.client.event.SelectClientEvent;
import sample.client.view.gxt.FilePanel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.inject.Inject;
import com.sencha.gxt.core.client.dom.XElement;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.widget.core.client.container.BoxLayoutContainer.BoxLayoutData;
import com.sencha.gxt.widget.core.client.container.CardLayoutContainer;
import com.sencha.gxt.widget.core.client.container.HBoxLayoutContainer;
import com.sencha.gxt.widget.core.client.container.HBoxLayoutContainer.HBoxLayoutAlign;
import com.sencha.gxt.widget.core.client.container.MarginData;
import com.sencha.gxt.widget.core.client.container.SimpleContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;

public class MainPanel extends SimpleContainer
{
  protected boolean showBorders;
  protected CardLayoutContainer contentPanel;

  private SearchPanel searchPanel;
  private FilePanel filePanel;

  private final ClientManagerServiceAsync cmService = GWT
      .create(ClientManagerService.class);

  private HBoxLayoutContainer createTitlebar() {
    final HBoxLayoutContainer retval =
        new HBoxLayoutContainer(HBoxLayoutAlign.MIDDLE);
    retval.setId("titlebar");
    Image image = new Image("logo.gif");
    retval.add(image, new BoxLayoutData(new Margins(0, 20, 0, 30)));
    final Label label = new Label();
    retval.add(label, new BoxLayoutData());

    cmService.getTitle(new AsyncCallback<String>() {
      @Override
      public void onSuccess(String result) {
        label.setText(result);
        Document.get().setTitle(result);
        retval.forceLayout();
      }

      @Override
      public void onFailure(Throwable caught) {}
    });

    return retval;
  }

  private void bind(final CMModel model) {
    HandlerManager eventBus = model.getEventBus();

    eventBus.addHandler(SelectClientEvent.TYPE,
        new SelectClientEvent.SelectClientHandler() {
          @Override
          public void onSelectClient(SelectClientEvent e) {
            new DocumentList(e.getClient(), filePanel.getStore());
          }
        });

    XElement fileView = filePanel.getFileListView().getElement();
    addDropListener(fileView, model);
  }

  @Inject
  public MainPanel(CMModel model, @Named("showBorders") boolean showBorders) {
    super();
    this.showBorders = showBorders;

    contentPanel = new CardLayoutContainer();
    contentPanel.setWidth(700);

    searchPanel = new SearchPanel(model);
    filePanel = new FilePanel(model);

    contentPanel.add(searchPanel, new MarginData(0));

    int sp = 20;

    VerticalLayoutContainer v = new VerticalLayoutContainer();

    v.add(createTitlebar(), new VerticalLayoutData(1, 60));
    v.add(contentPanel, new VerticalLayoutData(1, .5, new Margins(sp, sp,
        sp / 2, sp)));
    v.add(filePanel, new VerticalLayoutData(1, .5, new Margins(0, sp, sp, sp)));
    setWidget(v);
    bind(model);
  }

  public native void addDropListener(Element target, CMModel m) /*-{
		function noopHandler(e) {
			e = e || event;
			e.stopPropagation();
			e.preventDefault();
		}

		$wnd.addEventListener("dragover", noopHandler, false);
		$wnd.addEventListener("drop", noopHandler, false);

		function handleDrop(e) {
			e = e || window.event; // get window.event if e argument missing (in IE)   
			noopHandler(e);

			target.style.backgroundColor = "#FFFFFF";

			var dt = e.dataTransfer;
			var files = dt.files;
			for ( var i = 0; i < files.length; i++) {
				var file = files[i];

				var formData = new FormData();
				var code = m.@sample.client.CMModel::getClientCodeText()();
				if (code == null) {
					$wnd.alert("No client selected!");
					return;
				}
				formData.append('clientCode', code);
				formData.append('filename', file.name);
				formData.append("file", file);

				$wnd.$.ajax({
					type : 'POST',
					url : 'gupld',
					data : formData,
					contentType : false,
					processData : false,
					success : function(data) {
						m.@sample.client.CMModel::onClientNameChanged()();
					}
				});
			}
			return false;
		}

		function enterHandler(e) {
			target.style.backgroundColor = "#99FF99";
		}

		function dragLeaveHandler(e) {
			target.style.backgroundColor = "#FFFFFF";
			noopHandler(e);
		}

		// Drag events are: dragstart, drag, dragenter, *dragleave*, *dragover*, *drop* dragend

		target.addEventListener('dragenter', enterHandler, false);
		target.addEventListener('dragover', enterHandler, false);
		target.addEventListener('dragleave', dragLeaveHandler, false);
		target.addEventListener('drop', handleDrop, false);
  }-*/;
}
